from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers

from users.models import User


class PermissionSerializer(serializers.ModelSerializer):
    """权限序列化器类"""
    class Meta:
        model = Permission
        fields = '__all__'


class ContentTypeSerializer(serializers.ModelSerializer):

    class Meta:
        model = ContentType
        fields = ('id','name')

class GroupSerializer(serializers.ModelSerializer):
    """用户组序列化器类"""
    class Meta:
        model = Group
        fields = '__all__'

class PermSimpleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Permission
        fields = ('id','name')

class AdminUserSerializer(serializers.ModelSerializer):
    """管理员序列化器类"""
    class Meta:
        model = User
        fields = ('id','username','email','mobile','user_permissions','groups')

    extra_kwargs = {
        'password':{
            'write_only':True,
            'required':False,
            'allow_blank':True
        }
    }

    def create(self, validated_data):
        """创建管理员用户"""
        validated_data['is_staff'] = True
        # 创建新的管理员用户
        user = super().create(validated_data)
        password = validated_data.get('password')
        # 判断是否要默认密码,并加密保存
        if not password:
            # 管理员默认密码
            password = '123abc'

        user.set_password(password)
        user.save()

        return user

    def update(self, instance, validated_data):
        # 去除password
        password = validated_data.pop('password',None)
        # 修改
        super().update(instance,validated_data)
        # 修改密码
        if password:
            instance.set_password(password)
            instance.save()
        return instance

class GroupSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('id','name')
